package com.jjwxc.jwjskandriod.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.adapter.MoreBookViewHolder;
import com.jjwxc.jwjskandriod.config.BaseActivity;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.imageloader.FFImageLoader;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshView;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshViewFooter;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.UserRecomBook;
import com.jjwxc.jwjskandriod.readActivity.utils.StringUtils;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.jjwxc.jwjskandriod.widget.LinearLayouDecoration;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MoreBookActivity extends BaseActivity {

    private RecyclerView rv_morebook;
    private MoreBookAdapter adapter;
    private XRefreshView refreshView;
    public static long lastRefreshTime;
    //请求url
    private String url;
    //加载参数类型
    private String key;
    //参数值
    private String value;
    //条件
    private String channels;

    private int page = 0;

    @Override
    public int getContentViewId() {
        return R.layout.activity_morebook;
    }

    @Override
    public void findView() {
        refreshView = findViewById(R.id.morebook_view);
        rv_morebook = findViewById(R.id.rv_morebook);
    }

    @Override
    public void setListener() {
        refreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                page = 0;
                afterCreate(page,null);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page += 1;
                afterCreate(page * 10,null);
            }
        });
    }

    @Override
    public void afterCreate() {
        String name = getIntent().getStringExtra("MORE_Name");
        setTitle(name);
        url = getIntent().getStringExtra("MORE_Url");
        key = getIntent().getStringExtra("MORE_Key");
        value = getIntent().getStringExtra("MORE_Value");
        channels = getIntent().getStringExtra("MORE_Channels");
        rv_morebook.setNestedScrollingEnabled(false);
        rv_morebook.setFocusable(false);
        rv_morebook.setLayoutManager(new LinearLayoutManager(MoreBookActivity.this));
        rv_morebook.addItemDecoration(new LinearLayouDecoration(MoreBookActivity.this,
                LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));
        rv_morebook.getItemAnimator().setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
        adapter = new MoreBookAdapter(this);
        rv_morebook.setAdapter(adapter);

        refreshView.setPinnedTime(1000);
        refreshView.setMoveForHorizontal(true);
        refreshView.setPullRefreshEnable(true);
        refreshView.setPullLoadEnable(true);
        refreshView.setAutoLoadMore(true);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(MoreBookActivity.this));
        refreshView.enableReleaseToLoadMore(true);
        refreshView.enableRecyclerViewPullUp(true);
        refreshView.enablePullUpWhenLoadCompleted(true);
        // 设置上次刷新的时间
        refreshView.restoreLastRefreshTime(lastRefreshTime);

        afterCreate(0,"");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!StringUtils.isEmpty(value)&&value.equals("1")) {
            MobclickAgent.onEvent(this, UMConstant.SUGGEST_FENLEI_MORE_GUDAIYANQING);
        }
    }

    @Override
    public void onBackPressed(View v) {
        super.onBackPressed(v);
        if (!StringUtils.isEmpty(value)&&value.equals("1")) {
            MobclickAgent.onEvent(this, UMConstant.SUGGEST_FENLEI_MORE_GUDAIYANQING_BACK_CLICK);
        }
    }
    public void afterCreate(int page,String quan) {
        String request;
        if (key.equals("tab")) {
            request = "{\"offset\":" + page + ", \"limit\":10,\"tab\":\"" + value + "\"}";
        } else if (key.equals("book")) {
            request = "{\"offset\":" + page + ",\"limit\":10,\"bookId\":\"" + value + "\"}";
        } else if (key.equals("derivative")) {
            request = "{\"offset\":" + page + ",\"limit\":10,\"tab\":\"" + value + "\" ,\"channels\":[\"" + channels + "\"]}";
        } else if (key.equals("no")) {
            request = "{\"offset\":" + page + ",\"limit\":10}";
        } else {
            request = "{\"offset\":" + page + ",\"limit\":10}";
        }
        post(url, quan, UserRecomBook.class, new FFNetWorkCallBack<UserRecomBook>() {
            @Override
            public void onSuccess(UserRecomBook response) {
                lastRefreshTime = refreshView.getLastRefreshTime();
                if (response.getCode() == 200) {
                    if (response.getData() == null || response.getData().size() < 10) {
                        refreshView.setLoadComplete(true);
                    }
                    if (page == 0) {
                        refreshView.stopRefresh();
                        refreshView.setLoadComplete(false);
                        adapter.setData(response.getData());
                    } else {
                        refreshView.stopLoadMore();
                        adapter.addData(response.getData());
                    }
                }
            }

            @Override
            public boolean onFail(UserRecomBook response) {
                refreshView.stopLoadMore();
                refreshView.stopRefresh();
                refreshView.setLoadComplete(true);
                return false;
            }
        }, request);


    }


    public class MoreBookAdapter extends BaseRecyclerAdapter<MoreBookViewHolder> {
        private Context context;


        private List<UserRecomBook.DataBean> mData = new ArrayList<>();


        public MoreBookAdapter(Context cnt) {
            this.context = cnt;

        }

        public void addData(List<UserRecomBook.DataBean> data) {
            if (data != null) {
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<UserRecomBook.DataBean> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public MoreBookViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {

            View mView = LayoutInflater.from(context).inflate(R.layout.morebook_item, parent, false);
            MoreBookViewHolder viewHolder_text = new MoreBookViewHolder(mView);
            viewHolder_text.setIsRecyclable(false);
            return viewHolder_text;

        }

        @Override
        public MoreBookViewHolder getViewHolder(View view) {
            return new MoreBookViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @Override
        public void onBindViewHolder(final MoreBookViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {
            FFImageLoader.loadImage(context, holder.img_morebook_item, mData.get(position).getCoverImgUrl(), mData.get(position).getBookId(), true);
            holder.tv_bookname.setText(mData.get(position).getName());
            holder.tv_book_author.setText(mData.get(position).getAuthor());
            holder.tv_book_text.setText(StUtils.reBlank(mData.get(position).getBookIntro()));
            holder.tv_morebook_tab.setText(mData.get(position).getChannlname());
            holder.cl_morebook.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MoreBookActivity.this, BookDetailsActivity.class);
                    intent.putExtra("bookId", mData.get(position).getBookId());
                    startActivity(intent);

                }
            });


        }

        @Override
        public int getAdapterItemViewType(int position) {
            return position;
        }


        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }

    }
}